< previous page page_320 next page >

Page 320
0320-01.gif
Figure T4-2d:
The return address is popped from the stack 
when a function exits
As you can see, a stack is an essential part of the operation of any program. It is fundamental to the way subroutine and function calls operate. But this is only the beginning.
Passing a Parameter to a Function
Now let's consider what happens when a function has a parameter. In this case, we'll use a Long parameter, since it's 32 bits wide and allows us to ignore for the moment what happens when a parameter does not fit exactly on the stack.
Function B() may be unfamiliar to some Visual Basic programmers. The first time it is called in this example, parameter L has the value of 1, so the function calls itself again, this time with the value 0. This second time through, the function sees that the value of the parameter is 0 and exits immediately. When a function calls itself in this manner, it's called a recursive function. Recursion is sometimes used for math operations and for operations on certain types of data structures. Function B() code is as follows:
Function B(ByVal L As Long) As Long
   Debug.Print L
   If L = 0 Then Exit Function
   B = B(L - 1)
End Function

Sub Main()
   Call B(1)
End Sub
Figure T4-3a illustrates the stack immediately after Function B() is called for the first time. As you can see, the parameter to the function is placed on the stack just before the return address. When the function refers to variable L, it is referring to the value on the stack. When Function B() is called a second time, parameter L is once again placed on the stack, as shown in Figure T4-3b. This time, it has the value 0. Which of the two stack locations is the real parameter L? The answer is both. The instance of parameter L with the value 1 belongs to the first call to Function B(). The instance of parameter L with the value 0 belongs to the second call to Function B(). Every time the function is called, it has its own local copy of parameter L.

 
< previous page page_320 next page >